using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Collections;
using visAd.ExceptionHandler;
using System.IO;
using System.Configuration;

//using Microsoft.ConfigurationManagement.ManagementProvider.ConnectionManagerBase;

namespace visAd.ServerDataAddIn
{
    public partial class frmServerInfo : Form
    {
        private const string mClassName = "frmServerInfo";
        private static string userFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
        private static string configPath = userFolder + @"\Visio Add-In for System Center\ServerList.xml";

        private static string installPath = Utilities.AppPath() + @"\ConfigFiles\ServerList.xml";

        public frmServerInfo()
        {
            InitializeComponent();
        }

        private void frmServer_Load(object sender, EventArgs e)
        {
            try
            {

                XmlDocument doc = new XmlDocument();
                ArrayList arr = new ArrayList();
                string serverType = string.Empty;
                string serverId = string.Empty;

                arr.Add("SCOM");
                arr.Add("SCCM");

                //string serverType = string.Empty;
                DataTable dtServerInfo = new DataTable();
                dtServerInfo.Columns.Add("Server Type");
                dtServerInfo.Columns.Add("Server Name");
                //dtServerInfo.Columns.Add("Connection String");
                //XmlDocument doc = new XmlDocument();
                //doc.Load(Utilities.AppPath() + @"\ConfigFiles\ServerList.xml");
                if (File.Exists(configPath))
                {
                    doc.Load(configPath);

                }
                else if(File.Exists(installPath))
                {
                    File.Copy(installPath,configPath);
                    doc.Load(configPath);
                }
                else
                {
                    if (DialogResult.OK == MessageBox.Show("File: " + configPath + " not found. Please re-install the add-in.",
                        "",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error))
                    {
                        this.Close();
                    }
                    return;
                 }
                 
                 
                    XmlNodeList xmlList = doc.SelectNodes("/visAd/va-servertype/va-servers");
                    foreach (XmlNode node in xmlList)
                    {
                        if (node.ParentNode.Attributes.GetNamedItem("type").Value.ToString() != null)
                        {
                            if (node.Attributes.GetNamedItem("id").Value.ToString() != null)
                            {
                                //if (arr.Contains(node.ParentNode.Attributes.GetNamedItem("type").Value.ToString()))
                                //{
                                    DataRow row = dtServerInfo.NewRow();
                                    row["Server Type"] = node.ParentNode.Attributes.GetNamedItem("type").Value.ToString();
                                    row["Server Name"] = node.Attributes.GetNamedItem("id").Value.ToString();
                                    //if (docWeb.SelectSingleNode("/configuration/connectionStrings/add[@name = '" + node.ParentNode.Attributes.GetNamedItem("type").Value.ToString() + "']") != null)
                                    // {
                                    // XmlNode nodeConn = docWeb.SelectSingleNode("/configuration/connectionStrings/add[@name = '" + node.ParentNode.Attributes.GetNamedItem("type").Value.ToString() + "']");
                                    // row["Connection String"] = nodeConn.Attributes.GetNamedItem("connectionString").Value;
                                    //if (node.ParentNode.Attributes.GetNamedItem("type").Value.ToString() == "SCOM")
                                    //{
                                    //    row["Connection String"] = vaCustomException.SCOMConnectionString;
                                    //}
                                    //else if (node.ParentNode.Attributes.GetNamedItem("type").Value.ToString() == "SCCM")
                                    //{
                                    //    row["Connection String"] = vaCustomException.SCCMConnectionString;
                                    //}

                                    dtServerInfo.Rows.Add(row);
                               // }
                            }

                        }
                    }

                

                dataGridView1.AutoGenerateColumns = false;
                dataGridView1.DataSource = dtServerInfo;


                DataGridViewComboBoxColumn cbc = new DataGridViewComboBoxColumn();
                cbc.DataSource = arr;
                cbc.Name = "Server Type";
                cbc.DataPropertyName = "Server Type";
                dataGridView1.Columns.Add(cbc);

                DataGridViewTextBoxColumn serverIdColumn = new DataGridViewTextBoxColumn();
                serverIdColumn.Name = "Server Name";
                serverIdColumn.DataPropertyName = "Server Name";
                dataGridView1.Columns.Add(serverIdColumn);

                
                DataGridViewLinkColumn delColumn = new DataGridViewLinkColumn();
                delColumn.Text = "Delete";
                delColumn.HeaderText = "Delete";
                delColumn.ActiveLinkColor = System.Drawing.Color.Blue;

                delColumn.UseColumnTextForLinkValue = true;
                dataGridView1.Columns.Add(delColumn);
                //frmServerInfo serverfrm = new frmServerInfo(arr);

                ////this.Hide();
                //serverfrm.ShowDialog();
                

            }

            catch (Exception ex)
            {
                //throw new vaCustomException(ex, mClassName, "frmProvider_Load");
                vaCustomException vaExcep = new vaCustomException(ex, mClassName, "frmProvider_Load");
                vaExcep.WriteToLog(visAd.ServerDataAddIn.Properties.Settings.Default.LogFileDir, visAd.ServerDataAddIn.Properties.Settings.Default.IsFileLogRequired, visAd.ServerDataAddIn.Properties.Settings.Default.IsEventLogRequired);
            }

        }

        private void btnFinish_Click(object sender, EventArgs e)
        {
            try
            {
                //if (DialogResult.OK == MessageBox.Show("This will commit changes to Config file,\n Are you sure you want to commit these changes?", "Confirm Change", MessageBoxButtons.OKCancel))
                //{
                XmlDocument doc = new XmlDocument();
                XmlNode rootNode;
                //XmlElement addConnNode;
                XmlNode serverNode, serverIdNode;
                XmlAttribute type, id;
                ArrayList serverTypes = new ArrayList();
                string serverTypeValue = string.Empty;
                string serverId = string.Empty;
                bool formValidated = false;

               // doc.Load(Utilities.AppPath() + @"\ConfigFiles\ServerList.xml");
                if (File.Exists(configPath))
                {
                    doc.Load(configPath);

                }
                else if(File.Exists(installPath))
                {
                    File.Copy(installPath,configPath);
                    doc.Load(configPath);
                }
                else
                {
                    MessageBox.Show("File: " + configPath + " not found. Please re-install the add-in.",
                            "",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                    return;
                }


                    rootNode = doc.SelectSingleNode("/visAd");
                    rootNode.RemoveAll();
                    for (int index = 0; index < dataGridView1.RowCount - 1; index++)
                    {
                        serverTypeValue = dataGridView1.Rows[index].Cells[0].Value.ToString();
                        if (!serverTypes.Contains(serverTypeValue))
                        {
                            serverTypes.Add(serverTypeValue);
                        }
                    }
                    for (int count = 0; count < serverTypes.Count; count++)
                    {

                        serverNode = doc.CreateNode(XmlNodeType.Element, "va-servertype", "");
                        type = doc.CreateAttribute("type");
                        type.Value = serverTypes[count].ToString();
                        serverNode.Attributes.Append(type);
                        rootNode.AppendChild(serverNode);
                    }
                    for (int index = 0; index < dataGridView1.RowCount - 1; index++)
                    {
                        serverTypeValue = dataGridView1.Rows[index].Cells[0].Value.ToString();
                        serverId = dataGridView1.Rows[index].Cells[1].Value.ToString();
                        serverNode = doc.SelectSingleNode("/visAd/va-servertype[@type = '" + serverTypeValue + "']");
                        serverIdNode = doc.CreateNode(XmlNodeType.Element, "va-servers", "");
                        id = doc.CreateAttribute("id");
                        id.Value = serverId;
                        serverIdNode.Attributes.Append(id);
                        serverNode.AppendChild(serverIdNode);
                    }

                    //for (int index = 0; index < dataGridView1.RowCount - 1; index++)
                    //{
                    //    serverTypeValue = dataGridView1.Rows[index].Cells[0].Value.ToString();
                    //    serverId = dataGridView1.Rows[index].Cells[1].Value.ToString();
                    //    if (serverTypeValue == "SCOM")
                    //    {
                    //        vaConnectServer(serverId);
                    //    }
                    //    else if (serverTypeValue == "SCCM")
                    //    {
                    //        con = Connect(serverId);
                    //    }
                    //}

                    for (int index = 0; index < dataGridView1.RowCount - 1; index++)
                    {
                        serverTypeValue = dataGridView1.Rows[index].Cells[0].Value.ToString();
                        serverId = dataGridView1.Rows[index].Cells[1].Value.ToString();
                        if (serverTypeValue.Contains("SCOM"))
                        {
                            if (string.IsNullOrEmpty(serverId))
                            {
                                MessageBox.Show("Please enter the System Center Operations Manager Server Name.");                               
                                    dataGridView1.Focus();
                                    formValidated = true;
                                    break;
                               
                            }

                        }
                        if (serverTypeValue.Contains("SCCM"))
                        {
                            if (string.IsNullOrEmpty(serverId))
                            {
                                MessageBox.Show("Please enter the System Center Configuration Manager Server Name.");
                               
                                    dataGridView1.Focus();
                                    formValidated = true;
                                    break;
                               
                            }

                        }
                        if (!string.IsNullOrEmpty(serverId))
                        {
                            if (string.IsNullOrEmpty(serverTypeValue))
                            {
                              MessageBox.Show("Please select the server type either SCOM or SCCM.");
                               
                                    dataGridView1.Focus();
                                    formValidated = true;
                                    break;
                                
                            }
                        }
                    }

                    //doc.Save(Utilities.AppPath() + @"\ConfigFiles\ServerList.xml");
                    doc.Save(configPath);
                
                    visAdHelper.ServerListChanged = true;
                    //docWeb.Save(configPath);
                    //Application.Exit();
                    if (!formValidated)
                    {
                        this.Close();
                    }
                               
                // }
                // else
                //{
                //    MessageBox.Show(visAd.ServerDataAddIn.Properties.Settings.Default.NullError);
                //   // Application.Exit();
                //    this.Close();
                //}
            }

            catch (Exception ex)
            {
                // throw new vaCustomException(ex, mClassName, "btnFinish_Click");
                vaCustomException vaExcep = new vaCustomException(ex, mClassName, "btnFinish_Click");
                vaExcep.WriteToLog(visAd.ServerDataAddIn.Properties.Settings.Default.LogFileDir, visAd.ServerDataAddIn.Properties.Settings.Default.IsFileLogRequired, visAd.ServerDataAddIn.Properties.Settings.Default.IsEventLogRequired);

            }
        }
        /// <summary>
        /// Connects to an SDK Service by using the current user's credentials.
        /// </summary>
        //private void vaConnectServer(string srverID)
        //{
        //    try
        //    {

        //        mg = ManagementGroup.Connect(srverID);
        //        if (!mg.IsConnected)
        //        {
        //            throw new InvalidOperationException("Not connected to an SDK Service.");
        //        }
        //    }
        //    //catch (vaCustomException vaEx)
        //    //{
        //    //    vaEx.AddTrace(mClassName, "vaConnectServer");
        //    //    throw vaEx;
        //    //}
        //    catch (ConfigurationErrorsException ex)
        //    {
        //        //throw new vaCustomException(ex, mClassName, "vaConnectServer", "User does not have access permission.");
        //        MessageBox.Show("Failed to Connect SCOM Server. Error: " + ex.Message);
        //        return;

        //    }
        //    catch (Exception ex)
        //    {
        //        //throw new vaCustomException(ex, mClassName, "vaConnectServer", "Connection cannot be established with SCOM Server.");
        //        MessageBox.Show("Failed to Connect SCOM Server. Error: " + ex.Message);
        //        return;
        //    }
                    
        //}

        //public WqlConnectionManager Connect(string serverName)
        //{
        //    SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary();
        //    WqlConnectionManager connection = new WqlConnectionManager(namedValues);
        //    try
        //    {       connection.Connect(serverName);
        //            return connection;
        //    }
        //    //catch (SmsException ex)
        //    //{
        //        //MessageBox.Show("Failed to Connect. Error: " + ex.Message);
        //        //throw;
                
        //   // }

        //    //catch (UnauthorizedAccessException ex)
        //   // {
        //        //MessageBox.Show("Failed to authenticate. Error:" + ex.Message);
        //        //throw;
        //       // throw new vaCustomException(ex, mClassName, "vaConnectServer", "User does not have access permission.");
        //    //}
        //    catch (ConfigurationErrorsException ex)
        //    {
        //        //throw new vaCustomException(ex, mClassName, "vaConnectServer", "User does not have access permission.");
        //        MessageBox.Show("Failed to Connect SCCM Server. Error: " + ex.Message);
        //        return connection;
        //    }
        //    catch (Exception ex)
        //    {
        //        //throw new vaCustomException(ex, mClassName, "vaConnectServer", "Connection cannot be established with SCOM Server.");
        //        MessageBox.Show("Failed to Connect SCCM Server. Error: " + ex.Message);
        //        return connection;
        //    }
        //}

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
                       
            if (e.ColumnIndex == 2)
            {
                if (DialogResult.Yes == MessageBox.Show("Are you sure you want to delete?", "Confirm Change", MessageBoxButtons.YesNo))
                {
                    dataGridView1.Rows.Remove(dataGridView1.Rows[e.RowIndex]);
                }
            }
            
        }

        private void btnCancelServerConfig_Click(object sender, EventArgs e)
        {
            this.Close();
        }
               
    }
}